/**
 * QUANSHI.com Inc.
 * Copyright (c) 2016-2017 All Rights Reserved.
 */
package com.quanshi.scheduler.job.biz.route.strategy;

import java.util.ArrayList;

import com.quanshi.scheduler.core.base.Ret;
import com.quanshi.scheduler.core.biz.ExecutorBiz;
import com.quanshi.scheduler.core.biz.model.TriggerParam;
import com.quanshi.scheduler.core.rpc.netcom.jetty.NetComClientProxy;
import com.quanshi.scheduler.job.biz.route.ExecutorRouter;
import com.quanshi.scheduler.job.dal.entity.TriggerLog;

/**
 * 故障转移
 * 
 * @author yanxiang.huang 2017-07-10 13:36:10
 */
public class ExecutorRouteFailover extends ExecutorRouter
{

    @Override
    public String route( long jobId, ArrayList<String> addressList )
    {
        return addressList.get(0);
    }

    @Override
    public Ret<String> routeRun( TriggerParam triggerParam, ArrayList<String> addressList, TriggerLog jobLog )
    {
        StringBuffer beatResultSB = new StringBuffer();
        for (String address : addressList) {
            // beat
            Ret<String> beatResult = null;
            try {
                ExecutorBiz executorBiz = (ExecutorBiz) new NetComClientProxy(ExecutorBiz.class, address).getObject();
                beatResult = executorBiz.beat();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                beatResult = new Ret<String>(Ret.FAIL_CODE, e.getMessage() );
            }
            beatResultSB.append("<br>----------------------<br>")
                    .append("心跳检测：")
                    .append("<br>address：").append(address)
                    .append("<br>code：").append(beatResult.getCode())
                    .append("<br>msg：").append(beatResult.getMsg());

            // beat success
            if (beatResult.getCode() == Ret.SUCCESS_CODE) {
                jobLog.setExecutorAddress(address);

                Ret<String> runResult = runExecutor(triggerParam, address);
                beatResultSB.append("<br>----------------------<br>").append(runResult.getMsg());

                return new Ret<String>(runResult.getCode(), beatResultSB.toString());
            }
        }
        return new Ret<String>(Ret.FAIL_CODE, beatResultSB.toString());
    }

}
